package cn.bjxy.shishaolong.utils;

import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.system.exception.OperatorFailureException;
import cn.bjxy.shishaolong.system.user.entity.SysUserLocalAuthen;
import lombok.Setter;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 工具类
 *
 * @Author 时少龙
 * @Date 2019-04-01 14:14
 * @Version 1.0
 */
@Component
@PropertySource("classpath:config/system-config.properties")
public class SysUtil {

    @Value("${user.secret}")
    @Setter
    private String userSecret;

    /**
     * 密码为空，使用默认密码加密，不为空加密新密码
     *
     * @param localAuthen
     */
    public String encodePassWord(SysUserLocalAuthen localAuthen) {
        StringBuilder password = new StringBuilder(userSecret);
        if (StringUtils.isEmpty(localAuthen.getPassword())) {
            throw new OperatorFailureException(StatusCode.INFO_ERROR, "密码不能为空");
        }
        password.append(localAuthen.getPassword());
        password.append(localAuthen.getNo());
        return sha1Hex(password.toString());
    }

    /**
     * 对字符串做sha1加密
     *
     * @param str
     * @return
     */
    public String sha1Hex(String str) {
        return DigestUtils.sha1Hex(str);
    }

}
